<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/Home' }">用户管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/users' }">用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="main">
      <div class="displays">
        <el-input
          clearable
          class="el-input"
          v-model.trim="params.query"
          placeholder="请输入内容"
          @clear="getSearchUsers"
          @blur="getSearchUsers"
          @keydown.native.enter="getSearchUsers"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="getSearchUsers"
          ></el-button>
        </el-input>
        <el-row>
          <el-button type="primary" @click="dialogFormVisible = true"
            >添加用户</el-button
          >
        </el-row>
      </div>
      <template>
        <el-table :data="tableData" border style="width: 100%; margin: 20px 0">
          <el-table-column prop="id" label="*" width="60"> </el-table-column>
          <el-table-column prop="username" label="用户" width="180">
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="180">
          </el-table-column>
          <el-table-column prop="mobile" label="电话" width="180">
          </el-table-column>
          <el-table-column prop="role_name" label="角色" width="180">
          </el-table-column>
          <el-table-column prop="mg_state" label="状态" width="180">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="changeUserState(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="" label="操作" min-width="230">
            <template slot-scope="scope">
              <el-button type="success" @click="upDateUser(scope.row)">
                <i class="el-icon-edit"></i>
              </el-button>
              <el-button type="danger" @click="CloneUser(scope.row.id)">
                <i class="el-icon-delete-solid"></i
              ></el-button>
              <!-- DistUser -->
              <el-button type="warning" @click="DistUser(scope.row)"
                ><i class="el-icon-s-tools"></i
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 分页 -->
      <template>
        <div class="block">
          <!--size-change   当 pageSize 改变时会触发 -->
          <!-- current-change 当	currentPage 改变时会触发 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="params.pagenum"
            :page-sizes="[1, 2, 5, 10, 20]"
            :page-size="params.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalpage"
          >
          </el-pagination>
        </div>
      </template>
      <!-- 添加用户弹框 -->
      <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
        <el-form :model="form" ref="form" :rules="rules">
          <el-form-item
            label="用户名"
            prop="username"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="用户密码"
            prop="password"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.password"
              autocomplete="off"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item
            label="用户邮箱"
            prop="email"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="手机号"
            prop="mobile"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.mobile" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUsers">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 修改用户信息 -->
      <el-dialog title="编辑用户" :visible.sync="upDateFormVisible">
        <el-form :model="formselet" ref="form" :rules="rules">
          <el-form-item
            label="用户名"
            prop="username"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="formselet.username"
              disabled
              autocomplete="on"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="用户邮箱"
            prop="email"
            :label-width="formLabelWidth"
          >
            <el-input v-model="formselet.email" autocomplete="on"></el-input>
          </el-form-item>
          <el-form-item
            label="手机号"
            prop="mobile"
            :label-width="formLabelWidth"
          >
            <el-input v-model="formselet.mobile" autocomplete="on"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="upDateFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="SelectUser">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 权限分配 -->
      <el-dialog title="分配角色" :visible.sync="distributionUser">
        <el-form ref="form" :model="forms" label-width="100px">
          <el-form-item label="当前的用户：">
            <span class="span">{{ forms.name }}</span>
          </el-form-item>
          <el-form-item label="当前的角色：">
            <span class="span">{{ forms.role_name }}</span>
          </el-form-item>
          <el-form-item label="新分配的角色:">
            <el-select v-model="RoleNames" placeholder="请选择">
              <el-option
                value="item.roleName"
                v-model="item.roleName"
                v-for="(item, index) in role"
                :key="index"
                >{{ item.roleName }}</el-option
              >
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="distributionUser = false"
              >取消</el-button
            >
            <el-button @click="distributionUsers">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
  </template>
    
</div>
</div>
</template>


<script>
import {
  GetUserUrl,
  changeUserState,
  getAddUsers,
  upDateUsers,
  delUsers,
  DistUser,
  RoleUser,
} from "../../api/index";
export default {
  data() {
    // 验证条件
    let validateMobile = (rule, value, callback) => {
      let regmobile = /^[1]([3-9])[0-9]{9}$/;

      if (!regmobile.test(value)) {
        callback(new Error("手机号码输入不规范"));
      } else {
        callback();
      }
    };
    return {
      input: "",
      role: [],
      RoleNames: "",
      prop: ["index"],
      formselet: {
        id: "",
        username: "",
        email: "",
        mobile: "",
        value: "",
        role_id: 0,
      },
      forms: {
        id: 0,
        name: "",
        role_name: "",
        region: "",
      },
      tableData: [
        {
          id: 25,
          username: "tige117",
          mobile: "18616358651",
          type: 1,
          email: "tige112@163.com",
          create_time: "2017-11-09T20:36:26.000Z",
          mg_state: true, // 当前用户的状态
          role_name: "炒鸡管理员",
        },
        {
          id: 25,
          username: "tige117",
          mobile: "18616358651",
          type: 1,
          email: "tige112@163.com",
          create_time: "2017-11-09T20:36:26.000Z",
          mg_state: true, // 当前用户的状态
          role_name: "炒鸡管理员",
        },
      ],
      totalpage: 0, //总条目数
      // users: 0,
      params: {
        query: "",
        pagenum: 1, //页码
        pagesize: 2, //数据条数
      },
      dialogFormVisible: false, //显示隐藏添加用户按钮
      upDateFormVisible: false, //显示隐藏修改用户按钮
      distributionUser: false, //显示隐藏权限分配按钮
      form: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      formLabelWidth: "100px",
      //验证规则
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
        ],
        email: [{ required: true, message: "请输入用户邮箱", trigger: "blur" }],
        mobile: [
          { validator: validateMobile, trigger: "blur", required: true },
        ],
      },
    };
  },
  created() {
    this.getuser();
    this.getrole();
  },
  methods: {
    async getuser() {
      let {
        data: { pagenum, total, users },
      } = await GetUserUrl(this.params);
      this.totalpage = total;
      this.params.pagenum = pagenum;
      this.tableData = users;
    },
    // 处理权限的函数
    async getrole() {
      let { data } = await RoleUser();
      this.role = data;
      // console.log(this.role);
    },

    // 分页
    handleSizeChange(val) {
      this.params.pagesize = val;
      this.getuser();
    },
    handleCurrentChange(val) {
      this.params.pagenum = val;
      this.getuser();
    },
    //搜索功能
    getSearchUsers() {
      this.getuser();
    },
    // 状态变化
    async changeUserState(data) {
      // console.log({id:data.id,type:data.mg_state});
      let res = await changeUserState({ id: data.id, type: data.mg_state });
      // console.log(res);
      let {
        meta: { msg, status },
      } = res;
      if (status == 200) {
        this.$message({ type: "success", message: msg });
        // 刷新页面
        this.getuser();
      }
    },
    // 添加用户逻辑
    async addUsers() {
      // 表单的验证
      // 验证通过后 发送请求
      // 发送请求成功关闭弹框 重新渲染页面
      // 表单验证
      let success = await this.$refs["form"].validate().catch(() => {});
      console.log(success);

      if (!success) return false;

      // 验证通过后发送请求

      let {
        meta: { status },
      } = await getAddUsers(this.form);

      if (status == 201) {
        this.$message.success("添加成功！");
        // 关闭弹框
        this.dialogFormVisible = false;
      }
    },
    // 修改用户输入基本信息
    upDateUser(data) {
      // 点击时获取需要修改用户的id   用户名   ，邮箱   ，电话
      let { id, mobile, username, email } = data;
      this.formselet.id = id;
      this.formselet.username = username;
      this.formselet.email = email;
      this.formselet.mobile = mobile;
      this.upDateFormVisible = true;
    },
    // 修改数据
    async SelectUser() {
      // 验证修改的格式是否正确
      console.log(this.formselet);
      let obj = {
        id: this.formselet.id,
        email: this.formselet.email,
        mobile: this.formselet.mobile,
      };
      let res = await upDateUsers(obj);
      if (res) {
        this.getuser();
      }
      this.upDateFormVisible = false;
      // 发送请求 刷新页面
    },
    // 删除用户
    CloneUser(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delUsers(id);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getuser();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 分配权限
    DistUser(data) {
      this.forms.id = data.id;
      this.forms.name = data.username;
      this.forms.role_name = data.role_name;
      this.distributionUser = true;
    },
    // 分配权限
    async distributionUsers() {
      let data = this.role.filter((item) => {
        if (item.roleName == this.RoleNames) {
          return item;
        }
      });

      let obj = {
        id: this.forms.id,
        rid: data[0].id,
      };
      let {
        meta: { msg, status },
      } = await DistUser(obj);
      if (status == 200) {
        this.$message({ type: "success", message: msg });
        this.getuser();
        this.distributionUser = false;
      } else {
        this.$message({ type: "info", message: "修改失败！" });
      }
    },
  },
};
</script>
<style scoped lang='css'>
.el-breadcrumb {
  background-color: #eaedf1;
}
.displays {
  display: flex;
}
.el-input {
  width: 450px;
  margin-right: 15px;
}
.main {
  padding: 25px;
  background-color: #fff;
  height: auto;
}
.block {
  display: flex;
}
el-form-item {
  width: 100px;
}
.formuser {
  border: 1px solid red;
  display: flex;
  flex-direction: column;
  height: 200px;
}
.span {
  display: flex;
}
.el-select {
  display: flex;
  width: 200px;
}
.el-breadcrumb {
  padding-left: 0;
}
</style>